package Cau11;
import java.awt.EventQueue;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.net.MalformedURLException;
import java.rmi.Naming;
import java.rmi.NotBoundException;
import java.rmi.RemoteException;
import java.rmi.registry.LocateRegistry;

import javax.swing.JFrame;
import javax.swing.JButton;
import javax.swing.JLabel;


public class ServerStr extends Thread implements ActionListener{

	private JFrame frame;
	private JButton btnstart,btnstop;
	private JLabel lblmes;
	Thread t;
	/**
	 * Launch the application.
	 */
	public static void main(String[] args) {
		EventQueue.invokeLater(new Runnable() {
			public void run() {
				try {
					ServerStr window = new ServerStr();
					window.frame.setVisible(true);
				} catch (Exception e) {
					e.printStackTrace();
				}
			}
		});
	}

	/**
	 * Create the application.
	 */
	public ServerStr() {
		initialize();
		try {
			LocateRegistry.createRegistry(1099);
		} catch (RemoteException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

	/**
	 * Initialize the contents of the frame.
	 */
	private void initialize() {
		frame = new JFrame("Bai 10_Server");
		frame.setResizable(false);
		frame.setBounds(100, 100, 397, 195);
		frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
		frame.getContentPane().setLayout(null);
		
		btnstart = new JButton("Start");
		btnstart.addActionListener(this);
		btnstart.setBounds(79, 37, 89, 70);
		frame.getContentPane().add(btnstart);
		
		btnstop = new JButton("Stop");
		btnstop.addActionListener(this);
		btnstop.setBounds(227, 37, 89, 70);
		frame.getContentPane().add(btnstop);
		
		lblmes = new JLabel("");
		lblmes.setBounds(122, 118, 131, 23);
		frame.getContentPane().add(lblmes);
		
	}

	@Override
	public void actionPerformed(ActionEvent e) {
		if(e.getSource()==btnstart){
			t=new Thread(this);
			t.start();
			btnstart.setEnabled(false);
			btnstop.setEnabled(true);
			lblmes.setText("Server is running...");
		}
		if(e.getSource()==btnstop){
			try {
				Naming.unbind("rmi://localhost/ServerStr");
			} catch (RemoteException e1) {
				
				e1.printStackTrace();
			} catch (MalformedURLException e1) {
				
				e1.printStackTrace();
			} catch (NotBoundException e1) {
				
				e1.printStackTrace();
			}
			btnstart.setEnabled(true);
			btnstop.setEnabled(false);
			lblmes.setText("Server is stoped");
		}
		
	}
	public void run(){
		try {
			ProcessStringImpl psi=new ProcessStringImpl();
			Naming.rebind("rmi://localhost/ServerStr", psi);
		} catch (RemoteException e) {
			e.printStackTrace();
		} catch (MalformedURLException e) {
			e.printStackTrace();
		}
	}
}
